package com.acme.iolab.filesend.io;


import com.acme.iolab.filesend.FileClient;
import com.acme.iolab.filesend.IntToByteArrayConverter;

import java.io.*;
import java.net.Socket;

public class IOFileClient extends FileClient {

    public IOFileClient(String serverIp, int port) {
        super(serverIp, port);
    }

    @Override
    public void sendFile(String filePath) throws IOException {
        File myFile = new File(filePath);
        try (Socket socket = new Socket(serverIp, port);
             FileInputStream src = new FileInputStream(filePath);
             OutputStream os = socket.getOutputStream();
             BufferedReader in =
                     new BufferedReader(
                             new InputStreamReader(socket.getInputStream()))) {
            long start = System.currentTimeMillis();
            System.out.println("Connected to server.");

            int size = (int) myFile.length();
            byte[] buffer = new byte[size];
            byte[] sizeBuffer = IntToByteArrayConverter.convert(size);

            os.write(sizeBuffer, 0, 4);
            int n;
            while ((n = src.read(buffer)) != -1) {
                os.write(buffer, 0, n);
            }
            System.out.println("File sent");

            while ((in.readLine()) != null) {
                System.out.println("File sent in: " + (System.currentTimeMillis() - start));
            }
        }
    }
}
